package com.dtborad.myblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dtborad.myblog.common.CommonErrorCode;
import com.dtborad.myblog.common.Result;
import com.dtborad.myblog.entity.Posts;
import com.dtborad.myblog.service.PostService;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
@Slf4j
@Api(tags = "文章模块")
@CrossOrigin(origins = "*")
public class PostController {
    @Autowired
    private PostService postService;

    @Autowired
    private SensitiveWordBs sensitiveWordBs;

    // 文章列表
    @GetMapping("/list")
    public Result<Map<String, Object>> list(@RequestParam(defaultValue = "1") int pagenum,
                                            @RequestParam(defaultValue = "5") int pagesize,
                                            @RequestParam(defaultValue = "") Integer categoryid,
                                            @RequestParam(defaultValue = "") String content,
                                            @RequestParam(required = false) Integer userId) {
        Page<Posts> currentPage = postService.getAllPostsByPageSize(pagenum, pagesize, categoryid, content, userId);
        Map<String, Object> response = new HashMap<>();
        response.put("records", currentPage.getRecords());
        response.put("total", currentPage.getTotal());
        return Result.ofSuccess(response);
    }

    // 文章详情
    @GetMapping("/info/{id}")
    public Result<Posts> getDetail(@PathVariable Long id) {
        LambdaQueryWrapper<Posts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Posts::getPostid, id);
        return Result.ofSuccess(postService.getOne(wrapper));
    }

    //修改文章
    @PutMapping("/update")
    public Result<String> updateArticle(@RequestBody Posts posts) {
        try {
            //检验文章内容敏感词
            if (sensitiveWordBs.contains(posts.getContent())) {
                posts.setContent(sensitiveWordBs.replace(posts.getContent()));
            }
            Integer i = postService.updatePostById(posts);
            if (i != 0) return Result.ofFail(CommonErrorCode.DATABASE_ERROR);
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
        return Result.ofSuccess();
    }

    //删除文章
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteArticle(@PathVariable Long id) {
        try {
            LambdaQueryWrapper<Posts> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Posts::getPostid, id);
            postService.remove(wrapper);
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
        return Result.ofSuccess();
    }

    //新增文章
    @PostMapping("/add")
    public Result<String> addArticle(@RequestBody Posts posts) {
        try {
            //设置当前登录用户为文章作者
            Posts newPosts = new Posts();
            //检验敏感词
            if (sensitiveWordBs.contains(posts.getContent())) {
                posts.setContent(sensitiveWordBs.replace(posts.getContent()));
            }
            //将传递参数的属性拷贝到新对象中
            BeanUtils.copyProperties(posts, newPosts);
            //保存新对象
            postService.save(newPosts);
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
        return Result.ofSuccess();
    }

    //根据标签查询文章
    @GetMapping("/listByTag")
    public Result<List<Posts>> listArticleByTag(@RequestParam Integer tagid,
                                                @RequestParam String tagname) {
        try {
            LambdaQueryWrapper<Posts> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(Posts::getTags, tagname);
            List<Posts> list = postService.list(wrapper);
            return Result.ofSuccess(list);
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
    }
}
